﻿using Infrastructure.Model;
using Microsoft.Extensions.DependencyInjection;

using System.Reflection;

namespace Infrastructure.Extensions
{

    // 应用服务扩展类，用于注册程序集中带有 AppServiceAttribute 标记的服务类
    public static class AppServiceExtensions
    {
        public static void AddAppService(this IServiceCollection services, string[] AssemblyName)
        {
            foreach (string assemblyString in AssemblyName)
            {
                if (assemblyString == "Services")
                {
                    Console.WriteLine(assemblyString);
                }
                Assembly assembly = Assembly.Load(assemblyString);
                Register(services, assembly); // 调用注册方法
            }
        }

        private static void Register(IServiceCollection services, Assembly assembly)
        {
            try
            {

                Type[] types = assembly.GetTypes(); // 获取程序集中所有类型
                foreach (Type type in types)
                {
                    // 获取类上的 AppServiceAttribute 特性
                    AppServiceAttribute customAttribute = type.GetCustomAttribute<AppServiceAttribute>();
                    if (customAttribute != null)
                    {
                        Type serviceType = customAttribute.ServiceType; // 特性中指定的服务类型
                        if (serviceType == null && customAttribute.InterfaceServiceType)
                        {
                            // 如果未指定具体服务类型但标记了接口服务类型，则使用第一个实现的接口作为服务类型
                            serviceType = type.GetInterfaces().FirstOrDefault();
                        }
                        if (serviceType == null)
                        {
                            serviceType = type; // 默认情况下，服务类型为类本身
                        }

                        // 根据特性中指定的生命周期注册服务
                        switch (customAttribute.ServiceLifetime)
                        {
                            case LifeTime.Singleton:
                                services.AddSingleton(serviceType, type);
                                break;
                            case LifeTime.Scoped:
                                services.AddScoped(serviceType, type);
                                break;
                            case LifeTime.Transient:

                                services.AddTransient(serviceType, type);
                                Console.WriteLine(serviceType);
                                Console.WriteLine(type);

                                break;
                            default:
                                services.AddTransient(serviceType, type); // 默认为瞬态生命周期
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }
    }
}
